package nave.android.game;

import java.awt.Point;
import java.awt.geom.Point2D;
import nave.android.framework.Graphics;

public class AnimatedObject extends GameObject
{
	
	private static final long serialVersionUID = 1L;

	private Point2D framePos;
	private Point2D frameSize;
	public Point currentFrame = new Point(0, 0);
	private float timer;
	private float time;
	private int row, column;
	private boolean dependent;
	public boolean animate;
	private Asset texture;
	
	public AnimatedObject(Asset texture, Point2D p, Point2D d, Point2D sP, Point2D sD,
						  float time, Point animationType, boolean dependent)
	{
		super (texture, p, d);
		
		this.texture = texture;
		this.framePos = sP;
		this.frameSize = sD;
		this.time = time;
		row = animationType.x;
		column = animationType.y;
		this.dependent = dependent;
	}
	
	public void update(float deltaTime)
	{
		if (!dependent)
		{
			SimpleAnimation(deltaTime);
		}
		else
		{
			DependentAnimation(deltaTime);
		}
		super.Update();
	}
	
	public void SimpleAnimation(float deltaTime)
	{
		timer += deltaTime;
		if (timer > time)
		{
			if (currentFrame.x < row)
			{
				if (currentFrame.y < column - 1)
				{
					timer -= time;
					framePos = new Point2D.Double(framePos.getX() + frameSize.getX(), framePos.getY());
					currentFrame.y++;
				}
				else
				{
					timer -= time;
					framePos = new Point2D.Double(0, framePos.getY() + frameSize.getY());
					currentFrame.y = 0;
					currentFrame.x++;
				}
			}
		}
	}
	
	public void DependentAnimation(float deltaTime)
	{
		if (animate)
		{
			animate = false;
			timer += deltaTime;
			if (timer > time)
			{
				framePos = new Point2D.Double(framePos.getX(), frameSize.getY() * (currentFrame.x - 1));
				if (currentFrame.y < column - 1)
				{
					timer -= time;
					framePos = new Point2D.Double(framePos.getX() + frameSize.getX(), framePos.getY());
					currentFrame.y++;
				}
				else
				{
					timer -= time;
					framePos = new Point2D.Double(0, framePos.getY());
					currentFrame.y = 0;
				}
			}
		}
	}
	
	public void draw(Graphics g)
	{
		if (!animate)
		{
			super.Draw(g);
		}
		else
		{
			g.drawPixmap(texture,(int)this.posicao.getX(),
					 		     (int)this.posicao.getY(),
					 		     (int)this.framePos.getX(), 
					 		     (int)this.framePos.getY(), 
					 		     (int)(this.frameSize.getX()), 
					 		     (int)(this.frameSize.getY()));
			
		}
	}
}
